package cluster

import (
	"context"
	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"krm_backend/config"
	"krm_backend/utils"
	"krm_backend/utils/logs"
)

func Add_old(r *gin.Context) {
	logs.Debug(nil, "添加集群")
	clusterConfig := ClusterConfig{}
	returnData := config.NewReturnData()
	if err := r.ShouldBindJSON(&clusterConfig); err != nil {
		msg := "添加集群的配置信息不完整: " + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		return
	}
	// 开始创建之前，判断集群信息，用于验证传递的kubeconfig
	clusterStatus, err := clusterConfig.GetClusterStatus()
	if err != nil {
		msg := "无法获取集群信息: " + err.Error()
		returnData.Status = 400
		returnData.Message = msg
		r.JSON(200, returnData)
		logs.Error(map[string]interface{}{"error": err.Error()}, "添加集群失败，无法获取集群信息")
		return
	}

	logs.Info(map[string]interface{}{"集群名称": clusterConfig.DisplayName, "集群ID": clusterConfig.Id}, "开始添加集群")
	// 创建一个集群需要的secret
	var clusterConfigSecret corev1.Secret
	clusterConfigSecret.Name = clusterConfig.Id
	clusterConfigSecret.Labels = make(map[string]string)
	clusterConfigSecret.Labels["kubeasy.com/cluster.metadata"] = "true"
	// 添加注解
	//clusterConfigSecret.Annotations = make(map[string]string)
	//clusterConfigSecret.Annotations["displayName"] = clusterConfig.DisplayName
	//clusterConfigSecret.Annotations["city"] = clusterConfig.City
	//clusterConfigSecret.Annotations["district"] = clusterConfig.District
	m := utils.Struct2Map(clusterStatus)
	clusterConfigSecret.Annotations = m
	// 保存kubeconfig
	clusterConfigSecret.StringData = make(map[string]string)
	clusterConfigSecret.StringData["kubeconfig"] = clusterConfig.Kubeconfig
	// 创建secret
	_, err = config.InClusterClientSet.CoreV1().Secrets(config.MetadataNamespace).Create(context.TODO(), &clusterConfigSecret, metav1.CreateOptions{})
	if err != nil {
		// 创建失败
		logs.Error(map[string]interface{}{"集群Id": clusterConfig.Id, "集群名字": clusterConfig.DisplayName, "msg": err.Error()}, "集群创建失败")
		msg := "创建集群失败" + err.Error()
		returnData.Message = msg
		returnData.Status = 400
		r.JSON(200, returnData)
		return
	}
	logs.Info(map[string]interface{}{"集群ID": clusterConfig.Id, "集群名字": clusterConfig.DisplayName}, "集群创建成功")
	returnData.Status = 200
	returnData.Message = "添加成功"
	r.JSON(200, returnData)
}

func Add(r *gin.Context) {
	logs.Debug(nil, "添加集群")
	addOrUpdate(r, "Create")
}
